/* 
 * File:   LoginController.cpp
 * Author: user
 * 
 * Created on July 29, 2014, 9:54 PM
 */

#include <sqlite3.h>
#include <sstream>
#include "LoginController.h"

const string sql_DB = "CSCI222_A2.db";
const string LoginAccount_table = "LoginAccount";

static string _dbUserID, _dbLoginID, _dbPassword, _dbCreateBy;
static int _dbAcctType;
static bool _accountFound;

LoginController::LoginController() {
}

LoginController::LoginController(const LoginController& orig) {
}

LoginController::~LoginController() {
}

int LoginController::verifyLogin(string loginID,string pw,int userType, string& userID,string& createBy)
{
    int authenticateValue = -1;
    _accountFound = false;
      
    char * sqlAuth;
    sqlAuth = sqlite3_mprintf("SELECT * FROM %q WHERE LoginID='%q' AND AccountType='%d'", 
            LoginAccount_table.c_str(), loginID.c_str(), userType); 
    executeVerify(sqlAuth);
    
    if(pw == _dbPassword && _accountFound)
    {
        userID = _dbUserID;
        //_loginAccount.setLoginID(_dbLoginID);
        //_loginAccount.setPassword(pw);
        createBy = _dbCreateBy;
        //_loginAccount.setCreateBy(_dbCreateBy);
        
        authenticateValue = _dbAcctType;
    }

    return authenticateValue;  
}

bool LoginController::executeVerify(const char* sql) 
{
   sqlite3 *db;
   char *zErrMsg = 0;
   int rc;
   /* Open database */
   rc = sqlite3_open(sql_DB.c_str(), &db); 
   
   if( rc )
   {
      fprintf(stderr, "\n\nCan't open database: %s\n", sqlite3_errmsg(db));
      return false;
   }else{
      //fprintf(stderr, "Opened database successfully\n");
   }
           
   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql, authenticate, 0, &zErrMsg);   
   
   if( rc != SQLITE_OK )
   {
      fprintf(stderr, "\n\nSQL error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
      return false;
   }else{
      //fprintf(stdout, "retrieve data successfully\n");
   }
 
   return true;
   sqlite3_close(db);
}

int LoginController::authenticate (void *NotUsed, int argc, char **argv, char **azColName)
{
     string tempAcctType;
    _dbUserID = argv[1];
    _dbLoginID = argv[2];
    _dbPassword = argv[3];
    _dbCreateBy = argv[5];
    
    //decode password
    processPassword(_dbPassword);
   
    tempAcctType = argv[4];
    
    stringstream ss (tempAcctType);
    ss >> _dbAcctType;
   
    _accountFound = true;
    return 0;
}

void LoginController::processPassword(string& password)
{
    char key = 's';
    for (int i=0;i<password.size();i++)
        password[i] ^= (key + 255);
}

